<template>
  <div class="login">
    <div class="login-box" @click="changeImage(1)">
      <div class="auth-form">
        <div class="panfish">
          <img :src="imageURL" alt="">
        </div>
        <!-- 关闭按钮  -->
        <van-icon name="close" class="close-button" @click="close"></van-icon>

        <van-tabs animated
                  v-model="active">
          <van-tab title="登录">
            <van-cell-group v-show="!isShowSMSLogin">
          <!-- 账号密码登录 -->
              <!-- 手机号 -->
              <van-field
                v-model="login_userName"
                clearable
                required
                label="手机号码"
                maxlength="11"
                placeholder="请输入手机号码"
                @click.stop="changeImage(0)"
              >
              </van-field>

              <!-- 密码 -->
              <van-field
                v-model="login_password"
                type="password"
                required
                label="密码"
                autocomplete
                placeholder="请输入密码"
                @click.stop="changeImage(1)" />
              <van-field
                v-model="imgCaptcha"
                center
                clearable
                maxlength="4"
                placeholder="请输入验证码"
              >
              <!-- 图片验证码 -->
                <img
                  class="verificationImage"
                  src="http://demo.itlike.com/web/xlmc/api/captcha"
                  alt="captcha"
                  @click.prevent="getCaptcha"
                  ref="imgCaptcha"
                  slot="button"
                >
              </van-field>
            </van-cell-group>
            <!-- 手机号验证码登录 -->
            <van-cell-group v-show="isShowSMSLogin">
              <van-field  v-model="login_phone"
                          required
                          clearable
                          maxlength="11"
                          label="手机号"
                          placeholder="请输入手机号"
              />
              <van-field  v-model="smsCaptcha"
                          center
                          clearable
                          required
                          label="请输入验证码"
                          maxlength="6"
                          placeholder="请输入验证码">
                  <template #button>
                    <van-button size="small"
                                type="primary"
                                v-if="!countDown"
                                :disabled="captchaDisable"
                                @click="sendVerifyCode">发送验证码</van-button>
                    <van-button size="small"
                                type="primary"
                                disabled=""
                                v-model="smsCaptcha"
                                v-else>{{countDown}}s</van-button>
                  </template>
              </van-field>
            </van-cell-group>
            <van-button class="login-btn"
                        type="info"
                        size="large"
                        style="margin-top:17px"
                        @click.stop='login'>登录</van-button>
            <div class="switchLogin" @click="switchLogin">
              {{ this.isShowSMSLogin ? '账号密码登录' : '短信验证码登录' }}
            </div>
          </van-tab>
          <!-- 注册 -->
          <van-tab title="注册">
            <van-cell-group>
              <van-field v-model="register_phone"
                         clearable
                         maxlength="11"
                         label="手机号码"
                         placeholder="请输入手机号"
                         required />
              <van-field v-model="register_pwd"
                         type="password"
                         label="密码"
                         placeholder="请输入密码(不少于6位)"
                         required />
            </van-cell-group>
            <van-button class="register-btn"
                        type="info"
                        size="large"
                        style="margin-top: 17px"
                        @click='register'>注册</van-button>
          </van-tab>
        </van-tabs>
        <!-- 第三方登录 -->
        <van-divider :style="loadStyle">
          其他登录方式
        </van-divider>
        <van-grid :column-num="2" :border=false>
          <van-grid-item @click="thirdLogin(0)">
            <svg-icon iconClass="wechat" className="icon" />
            <div class="title">微信登录</div>
          </van-grid-item>
          <van-grid-item @click="thirdLogin(1)">
            <svg-icon iconClass="QQ" className="icon" />
            <div class="title">QQ登录</div>
          </van-grid-item>
        </van-grid>
         <!-- 底部声明 -->
        <p class="agreement">温馨提示：<br>未注册的手机号，登录时将自动注册，且代表同意
          <a @click.stop="agreement(0)"
            class="agreement-box">用户协议</a>、
          <a @click.stop="agreement(1)" class="agreement-box">隐私策略</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import Validator from '@/assets/js/validatorForm'
import { getPhoneCaptcha, phoneCaptchaLogin, pwdLogin } from '../../network/home'
import { mapGetters, mapActions, mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      countDown: 0, // 倒计时
      active: 0,
      login_userName: '', // 用户名
      login_password: '', // 用户密码
      login_phone: '',    // 手机号码

      register_phone: '', // 注册手机号
      register_pwd: '', // 注册密码

      imgCaptcha: '',  // 图片验证码
      smsCaptcha: '',   // 短信验证码
      isShowSMSLogin: true, // 是否短信登录

      switchLoginMsg: '账号密码登录',
      imageURL: require('../../assets/img/login/normal.png'),
      smsCaptchaResult: null,
      userInfo: null
    }
  },
  computed: {
    loadStyle () {
      return {
        color: '#1989fa',
        borderColor: '#1989fa',
        padding: '0 5px'
      }
    },
    // 发送验证码按钮显示
    captchaDisable () {
      if (this.phoneRegex(this.login_phone)) {
        return false
      }
      return true
    }
  },
  methods: {
    // 切换图片
    changeImage (index) {
      let imgUrl = {
        0: () => require('../../assets/img/login/greeting.png'),
        1: () => require('../../assets/img/login/blindfold.png'),
        'default': () => require('../../assets/img/login/normal.png')
      }
      this.imageURL = imgUrl[index]() || imgUrl['default']()
    },
    // 账号密码登录及短信验证码切换
    switchLogin () {
      this.isShowSMSLogin = !this.isShowSMSLogin
    },
    // 账号密码登录切换图片验证码
    getCaptcha () {
      // 获取验证码的标签
      let captchaEle = this.$refs.imgCaptcha
      this.$set(captchaEle, 'src', 'http://demo.itlike.com/web/xlmc/api/captcha?time=' + new Date())
    },
    // 获取手机验证码
    async sendVerifyCode () {
      this.countDown = 60
      this.timerId = setInterval(() => {
        this.countDown--
        this.countDown === 0 && clearInterval(this.timerId)
      }, 1000)
      // 获取短信验证码
      const result = await getPhoneCaptcha(this.login_phone)
      result.success_code === 200 && (this.smsCaptchaResult = result.data.code)
      // 获取验证码成功
      this.$dialog.alert({
          title: '温馨提示:',
          message: `验证码:${result.data.code}`
        }).then(() => {})
    },
     // 用户协议
    agreement (index) {
      if (index == 0) {
        this.$toast({
          message: '用户协议',
          duration: 800
        })
      } else {
        this.$toast({
          message: '隐私策略',
          duration: 800
        })
      }
    },
    close () {
      this.$router.back()
    },
    // 第三方登录
    thirdLogin (value) {
      if (value === 0) {
        this.$toast({
          message: '微信登录-暂未完成',
          duration: 800
        })
      } else {
        this.$toast({
          message: 'QQ登录-暂未完成',
          duration: 800
        })
      }
    },
    // 正则验证
    phoneRegex (number) {
      return (/[1][3,4,5,6,7,8][0-9]{9}$/.test(number))
    },
    // 登录
    async login () {
      const isShowErrMsg = this.loginValitorFn()
      if (this.isShowSMSLogin) {
        if (isShowErrMsg) {
          return false
        } else {
          // 请求后台登录接口
          console.log(this.login_phone)
          let ref = await phoneCaptchaLogin(this.login_phone, this.smsCaptcha)
          // 设置userInfo 保存到vuex和本地
          this.syncuserInfo(ref.data)
          this.$router.back()
        }
      } else {
        if (isShowErrMsg) {
          return false
        } else {
          let ref = await phoneCaptchaLogin(this.login_userName, this.login_password)
          this.syncuserInfo(ref.data)
          this.$router.back()
        }
      }
    },
    // 登录验证
    loginValitorFn () {
      const validator = new Validator()
      // 手机短信登录
      if (this.isShowSMSLogin) {
        validator.add(this.login_phone, [
        {
          strategy: 'isNonEmpty',
          errMsg: '手机号不能为空'
        },
        {
          strategy: 'isMobile',
          errMsg: '手机号格式不正确'
        }
      ])
      .add(this.smsCaptcha, [
        {
          strategy: 'minLength:5',
          errMsg: '请输入正确的验证码'
        }
      ])
      } else { // 账号密码登录
        validator.add(this.login_userName, [
        {
          strategy: 'isNonEmpty',
          errMsg: '手机号不能为空'
        },
        {
          strategy: 'isMobile',
          errMsg: '手机号格式不正确'
        }
      ])
      // 登录密码验证
      .add(this.login_password, [
        {
          strategy: 'isNonEmpty',
          errMsg: '密码不为空'
        },
        {
          strategy: 'minLength:5',
          errMsg: '密码不正确'
        }
      ])
      // 登录图片验证码
      .add(this.imgCaptcha, [
        {
          strategy: 'isNonEmpty',
          errMsg: '请输入正确的验证码'
        },
      ])
    }
      const result = validator.start()
      return result
    },
    // 注册验证
    registerValidatorFn () {
      const validator = new Validator()
      // 注册手机号验证
      validator.add(this.register_phone, [
        {
          strategy: 'isNonEmpty',
          errMsg: '手机号不能为空'
        },
        {
          strategy: 'isMobile',
          errMsg: '手机号格式不正确'
        }
      ])
      // 注册密码验证
      .add(this.register_pwd, [
        {
          strategy: 'isNonEmpty',
          errMsg: '密码不能为空'
        },
        {
          strategy: 'minLength:6',
          errMsg: '密码长度不能少于6位'
        }
      ])
      const result = validator.start()
      return result
    },
    // 注册
    async register () {
      const isShowErrMsg = this.registerValidatorFn()
      if (isShowErrMsg) {
        return false
      } else {
        let ref = await phoneCaptchaLogin(this.register_phone, this.register_pwd)
        this.syncuserInfo(ref.data)
        this.$toast({
          message: '注册成功',
          duration: 800
        })
        this.$router.back()
      }
    },
    // 同步用户信息
    ...mapActions(['syncuserInfo'])
  }
}
</script>
<style lang='scss' scoped>
.login {
  @include setAllcover(400);
  background-image: linear-gradient(125deg, #a55eea, #D980FA, #ED4C67, #9980FA, #d1d8e0);
  background-size: 400%;
  animation: bganimation 15s infinite;
  .login-box {
    @include flexType (center);
    @include setAllcover(500);
    opacity: .95;
    .auth-form {
      position: relative;
      width: px2rem(337);
      max-width: 90%;
      padding: px2rem(35);
      font-size: px2rem(20);
      background-color: #fff;
      border-radius: px2rem(8);
      img {
        position: absolute;
        z-index: 1;
        top: px2rem(18);
        left: 50%;
        width: px2rem(70);
        transform: translate(-50%, -70%);
        @media screen and (max-width: 320px) {
          top: px2rem(9);
          transform: translate(-50%, -40%);
          width: px2rem(88);
        }
      }
      .close-button {
        position: absolute;
        right: px2rem(17);
        top: px2rem(7);
      }
      .verificationImage {
        position: absolute;
        right: 0;
        @include setWH(px2rem(140), px2rem(52));
        margin-left: px2rem(52);
      }
      .switchLogin {
        margin-top: px2rem(17);
        font-size: px2rem(14);
      }
      .icon {
        @include setWH(px2rem(25), px2rem(25));
      }
    }
  }
  /deep/ .register-btn, .login-btn {
    background-image: linear-gradient(to left, #9980FA, #FDA7DF, #9980FA);
    background-size: 200%;
    border: none;
  }
  .title {
    padding: px2rem(8);
    @include setFontColor(px2rem(8), grey);
  }
  .agreement {
    line-height: px2rem(17);
    @include setFontColor(px2rem(15), #767676);
    .agreement-box {
      color: blue;
    }
  }
}
@keyframes bganimation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}
</style>
